#!/usr/bin/perl
use CGI;
use DBI;

our $serverip;
our $serverport;
our $rrdfilepath; 
our $rrdimgpath;
our $htmlfilepath;
our $mumonitorpath;
our $mumonitorcmdpath;
our $rrdtoolcmd;
our $db_hostname;
our $db_port;
our $db_name;
our $dsn;
our $username;
our $password;
our $SMTP_SERVER;
our $SENDER; 
our $bandwidth_in_mib;
our $bandwidth_out_mib;
our $bandwidth_2_in_mib;
our $bandwidth_2_out_mib;
our $total_swap_mib;
our $avail_swap_mib;
our $total_ram_mib;
our $avail_ram_mib;
our $load_1min_mib;
our $load_5min_mib;
our $load_15min_mib;
our $cpu_user_mib;
our $cpu_system_mib;
our $tcp_connection_mib;
our $update_mib;
our @rrd_name1;
our @rrd_name2;
our @application_list;

if ( -f "/www/mumonitor/monitor/mumonitor.conf") {
        require "/www/mumonitor/monitor/mumonitor.conf";
} else {
        dir("Mumonitor need configuration file not found! .\n");
}

my %query = parse_form_data ();
my $newfile="tmp.file";
my $oldfile="monitor.htm";

while ( ($key, $value) = each %query ) {
	if ($key eq 'AddServer') {
		print "Location: /input.htm\n\n";
	}
}

while ( ($key, $value) = each %query ) {
	open OLD, "<$mumonitorpath/$oldfile" or die "can't open $mumonitorpath/$oldfile: $!";
	open NEW, ">$mumonitorpath/$newfile" or die "can't open $mumonitorpath/$newfile: $!";
	if ($key eq "checkbox_$value") {
		chdir "$mumonitorpath" or die "cannot chdir to $mumonitorpath: $!";
		while (<OLD>) {
			if ( $_ =~ /\<\!--$value--\>/ ) {
				<OLD> for (1..31); 
			}else {
				print NEW $_;
			}
		}

		rename($newfile, $oldfile)      or die "can't rename $newfile to $oldfile: $!";

		$dbh = DBI->connect($dsn,$username,$password);
		$sql1 = "delete from mu_server where serverip='$value'";
		$sql2 = "delete from mu_monitor_server where serverip='$value'";
		$sql3 = "delete from mu_sshmessage  where serverip='$value'";
		$dbh->do("$sql1") or die $dbh->errstr;
		$dbh->do("$sql2") or die $dbh->errstr;
		$dbh->do("$sql3") or die $dbh->errstr;
		$dbh->disconnect;
		
		unlink glob "$rrdimgpath$value/* $rrdimgpath$value/.*";
		rmdir "$rrdimgpath$value";
	
		unlink glob "$htmlfilepath$value/* $htmlfilepath$value/.*";
		rmdir "$htmlfilepath$value";
		
		unlink glob "$rrdfilepath$value/* $rrdfilepath$value/.*";
		rmdir "$rrdfilepath$value";

	}
	close(OLD) or die "can't close $oldfile: $!";
	close(NEW) or die "can't close $newfile: $!";
}


print "Location: /monitor.htm\n\n";

sub parse_form_data {
	my %form_data;
	my $name_value;
	my @name_value_pairs = split /&/, $ENV{QUERY_STRING};
	foreach $name_value ( @name_value_pairs ) {
		my( $name, $value ) = split /=/, $name_value;
		$name =~ tr/+/ /;
		$name =~ s/%([\da-f][\da-f])/chr( hex($1) )/egi;
		$value = "" unless defined $value;
		$value =~ tr/+/ /;
		$value =~ s/%([\da-f][\da-f])/chr( hex($1) )/egi;
		$form_data{$name} = $value;
	}
    return %form_data;
}
